from functools import update_wrapper
import graphene
from flask import Flask
from flask_graphql import GraphQLView
import pymysql

def get_conn():
    db = pymysql.connect(host="localhost",port=3306,user='root',password='123',db='graphql',charset='utf8')
    cursor = db.cursor()
    return db,cursor

class Person(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()


class Query(graphene.ObjectType):
    persons = graphene.List(Person)

    def resolve_persons(self,info):
        sql = 'select * from t_user'
        d,c = get_conn()
        c.execute(sql)
        rs = c.fetchall()
        users = []
        for r in rs:
            users.append(Person(id=r[0],name=r[1]))
        c.close()
        d.close()
        return users

class DataInput(graphene.InputObjectType):
    id = graphene.ID()
    name = graphene.String()


class CreatePerson(graphene.Mutation):
    class Arguments:
        id = graphene.ID()
        name = graphene.String()

    flag = graphene.Boolean()
    def mutate(self,info,id,name):
        sql = 'insert into t_user values (%s,%s)'
        d,c = get_conn()
        rs = c.execute(sql,[id,name])
        d.commit()
        c.close()
        d.close()
        return CreatePerson( flag= True)

class CreatePerson2(graphene.Mutation):
    class Arguments:
        data_input = DataInput()

    flag = graphene.Boolean()
    def mutate(self,info,data_input):
        sql = 'insert into t_user values (%s,%s)'
        d,c = get_conn()
        rs = c.execute(sql,[data_input.get('id'),data_input.get('name')])
        d.commit()
        c.close()
        d.close()
        return CreatePerson( flag= True)

class UpdatePerson(graphene.Mutation):
    class Arguments:
        id = graphene.ID()
        name = graphene.String()

    flag = graphene.Boolean()
    def mutate(self,info,id,name):
        sql = 'update t_user set name = %s where id = %s'
        d,c = get_conn()
        rs = c.execute(sql,[name,id])
        d.commit()
        c.close()
        d.close()
        return CreatePerson( flag= True)

class DeletePerson(graphene.Mutation):
    class Arguments:
        id = graphene.ID()

    flag = graphene.Boolean()
    def mutate(self,info,id):
        sql = 'delete from t_user where id = %s'
        d,c = get_conn()
        rs = c.execute(sql,[id])
        d.commit()
        c.close()
        d.close()
        return CreatePerson( flag= True)

class Mutation(graphene.ObjectType):
    create_person = CreatePerson.Field()
    create_person2 = CreatePerson2.Field()
    update_person = UpdatePerson.Field()
    delete_person = DeletePerson.Field()

if __name__ =='__main__':
    schema = graphene.Schema(query=Query,mutation=Mutation)
    app = Flask(__name__)
    app.add_url_rule('/graphql',view_func=GraphQLView.as_view('grapql',schema=schema, graphiql=True))
    app.run(debug=True)